package com.hnchances.service.impl;

import com.hnchances.entity.User;
import com.hnchances.entity.Student;
import com.hnchances.exception.LoginException; // 引入自定义异常
import com.hnchances.mapper.LoginMapper;
import com.hnchances.service.LoginService;
import com.hnchances.vo.RegisterRequest;
import com.hnchances.vo.UpdateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean register(RegisterRequest request) {
        // 验证验证码
        String code = redisTemplate.opsForValue().get("verify_code:" + request.getPhone());
        if (code == null || !code.equals(request.getVerifyCode())) {
            throw new LoginException("验证码错误");
        }

        // 删除已使用的验证码
        redisTemplate.delete("verify_code:" + request.getPhone());

        // 创建用户对象
        User user = new User();
        user.setUserName(request.getPhone());
        user.setPassWord(hashPassword(request.getPhone())); // 使用哈希加密密码
        user.setPhone(request.getPhone());
        user.setTrueName(request.getName());
        user.setCreatDateTime(new Date());
        user.setUpdateDateTime(new Date());
        user.setStatus((short) 0);
        user.setVerify((short) 0);

        // 根据身份类型设置不同的字段
        if (request.getIdentity() == 0) {
            // 学生注册
            user.setIdentity((short) 0);
            Student student = loginMapper.selectStudentByIdcard(request.getIdcard());
            if (student == null) {
                throw new LoginException("该身份证号对应的学籍不存在");
            }
            user.setStudentID(student.getId().intValue());
        } else if (request.getIdentity() == 1) {
            // 老师注册
            user.setIdentity((short) 1);
            user.setClassID(request.getClassId());
            user.setCourseID(request.getCourseId());
        }

        // 插入用户
        loginMapper.insertUser(user);
        return true;
    }

    // 密码哈希加密方法
    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] byteData = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : byteData) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("密码加密失败", e);
        }
    }

    @Override
    public boolean update(UpdateRequest request) {
        // 获取用户信息
        User user = loginMapper.selectById(Long.valueOf(request.getId()));
        if (user == null) {
            throw new LoginException("用户不存在");
        }

        // 更新用户信息
        user.setTrueName(request.getName());
        user.setPhone(request.getPhone());
        user.setClassID(request.getClassId());
        user.setCourseID(request.getCourseId());
        user.setStudentID(request.getStudentId());
        user.setUpdateDateTime(new Date());

        // 执行更新操作
        loginMapper.updateUser(user);
        return true;
    }
}